rm(list = ls())

library(tidyverse)

## Get saved results

res_df_rdd_muni <- read_rds('data/rdd_municipal_results.rds') %>% 
  mutate(unit = 'Municipal\nelection')%>% 
  filter(str_detect(outcome, "total|turnout"))

res_df_rdd_bundestag <- read_rds('data/rdd_federal_results.rds') %>% 
  mutate(unit = 'Federal\nelection') %>% 
  mutate(outcome = str_remove(outcome, "_party")) %>% 
  filter(str_detect(outcome, "total|turnout"))

res_df_rdd_landtag <- read_rds('data/rdd_state_results.rds') %>% 
  mutate(unit = 'State\nelection') %>% 
  filter(str_detect(outcome, "total|turnout"))

## Clean and do some renaming

results_rdd <- list(res_df_rdd_landtag, 
                    res_df_rdd_bundestag, 
                    res_df_rdd_muni)%>% 
  reduce(bind_rows) %>%
  mutate(bw_type = ifelse(bw %% 500 == 0, 'regular', 'opt_bw')) %>%
  filter(!str_detect(outcome, 'cand')) %>% 
  mutate(exclude_state = ifelse(exclude_state == "State excluded",
                                'B-W excluded', 'Full sample')) %>% 
  mutate(outcome= recode(outcome, 
                         `left_total` = 'Left-wing parties',
                         `turnout` = 'Turnout',
                         `right_total` = 'Right-wing parties')) %>% 
  mutate(unit = factor(unit, levels = c('Federal\nelection',
                                        'State\nelection',
                                        'Municipal\nelection')))

## We only look at aggregate left and right, as well as turnout

results_rdd_3parties <- results_rdd %>%
  filter(outcome %in% c('Left-wing parties', 'Right-wing parties', 'Turnout'))
  
## Figure A.8: Main results, left/right/turnout ----

pd <- position_dodge(0.5)

p1 <- ggplot(results_rdd_3parties %>% filter(bw_type == 'opt_bw'), 
             aes(unit, estimate, outcome)) +
  geom_hline(yintercept = 0, linetype = 'dotted',
             color = 'grey40') +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high,
                    color = outcome), position = pd,
                width = 0, size = 0.65) +
  geom_errorbar(aes(ymin = conf.low90, ymax = conf.high90,
                    color = outcome), position = pd,
                width = 0, size = 1.05) +
  geom_point(aes(shape = outcome), position = pd,
             fill = 'white', size = 2.5) +
  scale_color_grey(name = '') + 
  scale_shape_manual(name = '', values = c(21, 22, 23)) +
  xlab('') +ylab('RD estimate\n(percentage points)')+ theme_bw() +
  theme(legend.position = 'bottom') +
  facet_wrap(~exclude_state, ncol = 2) +
  theme(legend.key.width = unit(1, 'cm'))
p1